<script setup>
import { ref } from 'vue'
import axios from 'axios'
import { ElMessage } from 'element-plus'
import { useUserStore } from '@/stores/user'

const userStore = useUserStore()

// 正面
const frontUploading = ref(false)
const frontPreviewUrl = ref('')
const frontFile = ref(null)
const frontDialog = ref(false)
const frontResult = ref(null)

// 反面（仅上传与识别，不展示结果）
const backUploading = ref(false)
const backPreviewUrl = ref('')
const backFile = ref(null)

const globalLoading = ref(false)
const submitting = ref(false)

// TODO: 替换为你的七牛空间访问域名（含协议）
const QINIU_DOMAIN = 'https://your-cdn-domain'

const beforeUpload = (file) => {
  const isImage = file.type === 'image/jpeg' || file.type === 'image/png' || file.type === 'image/jpg'
  if (!isImage) {
    ElMessage.error('仅支持 JPG/PNG 图片')
    return false
  }
  return true
}

const onFrontChange = (file) => {
  frontFile.value = file.raw
  frontPreviewUrl.value = URL.createObjectURL(file.raw)
}
const onBackChange = (file) => {
  backFile.value = file.raw
  backPreviewUrl.value = URL.createObjectURL(file.raw)
}

// 统一识别按钮：正面弹窗展示；反面仅识别不展示
const submitAll = async () => {
  if (!frontFile.value && !backFile.value) {
    ElMessage.warning('请至少上传正面或反面图片')
    return
  }
  globalLoading.value = true
  try {
    // 正面
    if (frontFile.value) {
      frontUploading.value = true
      const fd = new FormData()
      fd.append('image', frontFile.value)
      fd.append('side', 'front')
      const res = await axios.post('http://127.0.0.1:8888/idcard/verify', fd, { headers: { 'Content-Type': 'multipart/form-data' } })
      frontResult.value = res.data
      frontDialog.value = true
    }
    // 反面（不展示结果）
    if (backFile.value) {
      backUploading.value = true
      const fd2 = new FormData()
      fd2.append('image', backFile.value)
      fd2.append('side', 'back')
      await axios.post('http://127.0.0.1:8888/idcard/verify', fd2, { headers: { 'Content-Type': 'multipart/form-data' } })
    }
  } catch (e) {
    ElMessage.error(e?.response?.data?.detail || '识别失败')
  } finally {
    frontUploading.value = false
    backUploading.value = false
    globalLoading.value = false
  }
}

// 上传到七牛
const uploadToQiniu = async (file) => {
  const { data: token } = await axios.get('http://127.0.0.1:8888/qiniu/token', { responseType: 'text' })
  const form = new FormData()
  form.append('file', file)
  form.append('token', token)
  // 可选：自定义 key
  // form.append('key', Date.now() + '_' + file.name)
  const resp = await axios.post('https://upload.qiniup.com', form, { headers: { 'Content-Type': 'multipart/form-data' } })
  const key = resp.data.key
  const url = QINIU_DOMAIN ? `${QINIU_DOMAIN}/${key}` : key
  return url
}

// 提交实名信息到后端
const submitRealname = async () => {
  if (!frontResult.value?.parsed) {
    ElMessage.warning('请先完成正面识别')
    return
  }
  if (!frontFile.value) {
    ElMessage.warning('缺少正面图片文件')
    return
  }
  try {
    submitting.value = true
    // 1) 上传图片到七牛
    const imageUrl = await uploadToQiniu(frontFile.value)
    // 2) 组织入库数据
    const userId = userStore.userInfo?.id ? parseInt(userStore.userInfo.id) : 0
    const payload = {
      user_id: userId,
      image_url: imageUrl,
      name: frontResult.value.parsed.name,
      id_number: frontResult.value.parsed.id_number,
      address: frontResult.value.parsed.address,
    }
    // 3) 提交到后端
    await axios.post('http://127.0.0.1:8888/realname/submit', payload)
    ElMessage.success('实名信息已保存')
    frontDialog.value = false
  } catch (e) {
    ElMessage.error(e?.response?.data?.detail || '提交失败')
  } finally {
    submitting.value = false
  }
}
</script>

<template>
  <div class="home-container">
    <div class="idcard-box">
      <h2 class="title">身份证验证</h2>
      <p class="subtitle">正面与反面各自上传，使用同一按钮一键识别（仅展示正面结果）</p>

      <div class="grid">
        <!-- 正面 -->
        <div class="panel">
          <h3 class="panel-title">正面</h3>
          <el-upload
            class="uploader"
            action=""
            :show-file-list="false"
            :auto-upload="false"
            :before-upload="beforeUpload"
            :on-change="onFrontChange"
            accept="image/*"
          >
            <div class="upload-slot">
              <img v-if="frontPreviewUrl" :src="frontPreviewUrl" class="preview" />
              <div v-else class="placeholder">点击或拖拽上传身份证正面</div>
            </div>
          </el-upload>
        </div>

        <!-- 反面（国徽） -->
        <div class="panel">
          <h3 class="panel-title">反面（国徽）</h3>
          <el-upload
            class="uploader"
            action=""
            :show-file-list="false"
            :auto-upload="false"
            :before-upload="beforeUpload"
            :on-change="onBackChange"
            accept="image/*"
          >
            <div class="upload-slot">
              <img v-if="backPreviewUrl" :src="backPreviewUrl" class="preview" />
              <div v-else class="placeholder">点击或拖拽上传身份证反面</div>
            </div>
          </el-upload>
        </div>
      </div>

      <div class="actions">
        <el-button type="primary" :loading="globalLoading" :disabled="globalLoading" @click="submitAll">
          {{ globalLoading ? '识别中...' : '开始识别' }}
        </el-button>
      </div>
    </div>

    <!-- 正面结果（无原始返回，仅显示关键信息并提供提交按钮） -->
    <el-dialog v-model="frontDialog" title="正面识别结果" width="560px">
      <div v-if="frontResult">
        <el-descriptions :column="1" border>
          <el-descriptions-item label="姓名">{{ frontResult.parsed?.name || '-' }}</el-descriptions-item>
          <el-descriptions-item label="身份证号">{{ frontResult.parsed?.id_number || '-' }}</el-descriptions-item>
          <el-descriptions-item label="地址">{{ frontResult.parsed?.address || '-' }}</el-descriptions-item>
          <el-descriptions-item label="出生/民族">
            <span>{{ frontResult.parsed?.birth || '-' }}</span>
            <span v-if="frontResult.parsed?.nation">（{{ frontResult.parsed?.nation }}）</span>
          </el-descriptions-item>
        </el-descriptions>
        <div class="dialog-actions">
          <el-button type="primary" :loading="submitting" :disabled="submitting" @click="submitRealname">提交实名</el-button>
          <el-button @click="frontDialog = false">取消</el-button>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<style scoped>
.home-container { padding: 24px; }
.idcard-box { max-width: 960px; margin: 0 auto; background: #fff; border-radius: 10px; box-shadow: 0 10px 30px rgba(0,0,0,0.05); padding: 20px; }
.title { margin: 0; font-size: 20px; }
.subtitle { margin: 6px 0 16px; color: #909399; font-size: 13px; }
.grid { display: grid; grid-template-columns: 1fr 1fr; gap: 16px; }
.panel { background: #fafafa; border-radius: 8px; padding: 16px; }
.panel-title { margin: 0 0 10px; font-size: 16px; }
.uploader { width: 100%; margin-bottom: 12px; }
.upload-slot { width: 100%; height: 220px; border: 1px dashed var(--el-border-color); border-radius: 8px; display: flex; align-items: center; justify-content: center; overflow: hidden; }
.placeholder { color: #a8abb2; }
.preview { max-width: 100%; max-height: 100%; object-fit: contain; }
.actions { margin-top: 8px; text-align: center; }
.dialog-actions { margin-top: 14px; text-align: right; }
@media (max-width: 768px) { .grid { grid-template-columns: 1fr; } }
</style>
